package com.newmacys.tiles;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tiles.TilesApplicationContext;
import org.apache.tiles.context.TilesRequestContextFactory;
import org.apache.tiles.definition.DefinitionsFactoryException;
import org.apache.tiles.factory.AbstractTilesContainerFactory;
import org.apache.tiles.factory.BasicTilesContainerFactory;
import org.apache.tiles.startup.AbstractTilesInitializer;
import org.apache.tiles.startup.TilesInitializer;
import org.apache.tiles.web.startup.AbstractTilesInitializerServlet;

/**
 * Servlet implementation class TilesServlet
 */
public class TilesServlet extends AbstractTilesInitializerServlet {
	private static final long serialVersionUID = 1L;
       
    public TilesServlet() {
        super();
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	protected TilesInitializer createTilesInitializer() {
		return new TestAlternateTilesInitializer();
	}

    /**
     * Test Tiles initializer for Tiles initialization of the alternate container.
     */
    private static class TestAlternateTilesInitializer extends AbstractTilesInitializer {

		@Override
		protected AbstractTilesContainerFactory createContainerFactory(
				TilesApplicationContext arg0) {

			return new CustomTilesContainerFactory();
		}
    }


	private static class CustomTilesContainerFactory extends
			BasicTilesContainerFactory {

		protected List<URL> getSourceURLs(
				TilesApplicationContext applicationContext,
				TilesRequestContextFactory contextFactory) {
			try {

				List<URL> tilesUrls = new ArrayList<URL>();

				System.out.println("*************Preparing to load tiles configuration*******************");

				tilesUrls.add(applicationContext.getResource("/WEB-INF/tiles.xml"));

				Iterator it = null;
				it = tilesUrls.iterator();

				while (it.hasNext()) {
					URL url = (URL) it.next();
					System.out.println(url.getPath());
				}
				System.out.println("***********Completed loading tiles configuration*****************");

				return tilesUrls;

			} catch (IOException e) {
				throw new DefinitionsFactoryException(
						"Cannot load definition URLs", e);
			}

		}

	}

}
